import 'package:extended_tabs/extended_tabs.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:yp/config/index.dart';
import 'package:yp/config/style.dart';
import 'package:yp/widgets/bottom_sheet.dart';
import 'package:yp/widgets/button_widget.dart';
import 'package:yp/widgets/index.dart';

class CollectCouponsCenter extends StatefulWidget {
  const CollectCouponsCenter({Key key}) : super(key: key);

  @override
  _CollectCouponsCenterState createState() => _CollectCouponsCenterState();
}

class _CollectCouponsCenterState extends State<CollectCouponsCenter>
    with SingleTickerProviderStateMixin {
  TabController _controller;

  var _tabList = [Tab(text: '领券中心'), Tab(text: '我的优惠券')];

  List<Map<String, dynamic>> _couponsList = [
    {
      //是否折扣券
      'discount': true,
      // 折扣/面额
      'num': '3',
      // 条件
      'tips': '满39元可用',
      // 已抢
      'receive': '50',
      // 最多几张
      'maxHave': '3',
      // 已经领取几张
      'have': '1'
    },
    {
      'discount': false,
      'num': '30',
      'tips': '部分商品可用',
      'receive': '80',
      'maxHave': '3',
      'have': '0',
      'used': '0'
    },
    {
      'discount': true,
      'num': '3',
      'tips': '满39元可用',
      'receive': '5',
      'maxHave': '3',
      'have': '3',
      'used': '0'
    },
    {
      'discount': false,
      'num': '30',
      'tips': '部分商品可用',
      'receive': '100',
      'maxHave': '3',
      'have': '0',
      'used': '0'
    },
    {
      'discount': false,
      'num': '30',
      'tips': '部分商品可用',
      'receive': '20',
      'maxHave': '3',
      'have': '3',
      'used': '3'
    },
    {
      'discount': true,
      'num': '3',
      'tips': '满39元可用',
      'receive': '100',
      'maxHave': '3',
      'have': '1',
      'used': '1'
    },
    {
      'discount': false,
      'num': '30',
      'tips': '部分商品可用',
      'receive': '70',
      'maxHave': '3',
      'have': '0',
      'used': '0'
    },
    {
      'discount': false,
      'num': '30',
      'tips': '部分商品可用',
      'receive': '70',
      'maxHave': '3',
      'have': '0',
      'used': '0'
    },
    {
      'discount': false,
      'num': '30',
      'tips': '部分商品可用',
      'receive': '70',
      'maxHave': '3',
      'have': '0',
      'used': '0'
    }
  ];

  @override
  void initState() {
    super.initState();
    _controller =
        TabController(initialIndex: 0, length: _tabList.length, vsync: this);
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.init(
        BoxConstraints(
            maxWidth: MediaQuery.of(context).size.width,
            maxHeight: MediaQuery.of(context).size.height),
        designSize: Size(750, 1334),
        orientation: Orientation.portrait);
    return Scaffold(
        appBar: YPNavigationBar('领券中心'),
        body: Column(
          children: [
            _orderList(),
            _tabFooter(),
          ],
        ));
  }

  ///  tab栏切换的footer
  Widget _tabFooter() {
    return Container(
      color: EsColors.White,
      padding: EdgeInsets.fromLTRB(30.w, 0, 30.w,
          MediaQuery.of(context).padding.bottom == 4.w ? 0 : 40.w),
      child: ExtendedTabBar(
        tabs: List<Widget>.generate(
            _controller.length, (int index) => _tabList[index]),
        controller: _controller,
        labelPadding: EdgeInsets.zero,
        labelColor: EsColors.Money,
        isScrollable: _controller.length > 5,
        unselectedLabelColor: EsColors.ContentSecondary,
        indicatorSize: TabBarIndicatorSize.label,
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        indicator: const ExtendedUnderlineTabIndicator(
            // size: 30,
            borderSide: BorderSide(color: EsColors.Money, width: 2)),
      ),
    );
  }

  /// 上边对应的列表
  Widget _orderList() {
    return Expanded(
      child: TabBarView(
          controller: _controller,
          children: List<Widget>.generate(
              _controller.length,
              (int index) => ListView.separated(
                  padding: EdgeInsets.all(24.w),
                  itemBuilder: (context, index) {
                    return _coupon(_couponsList[index]);
                  },
                  separatorBuilder: (context, index) {
                    return SizedBox(height: 10);
                  },
                  itemCount: _couponsList?.length ?? 0)).toList()),
    );
  }


  /// 券item
  Widget _coupon(Map<String, dynamic> info) {
    return GestureDetector(
      onTap: () {
        YpBottomSheet.showCouponDetial(context, ({info}) {});
      },
      child: Container(
        padding: EdgeInsets.all(20.w),
        decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(10.w),
            image: DecorationImage(
                fit: BoxFit.fill,
                image: AssetImage('assets/images/coupon_1.png'))),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: [
            Image.asset(
                info['discount']
                    ? 'assets/images/discountCoupon_image.png'
                    : 'assets/images/priceCoupon_image.png',
                width: 100.w,
                height: 70.w),
            SizedBox(width: 24.w),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: [
                  SizedBox(height: 14.w),
                  Text(
                    info['discount']
                        ? '[折扣券]线下绿地超市部分商品可用'
                        : '[现金券]嘉定万达开业活动部分商品可用',
                    style: TextStyle(
                        color: EsColors.Title,
                        fontSize: EsSizes.SM * 2.sp,
                        fontWeight: EsFontWeights.Medium),
                  ),
                  SizedBox(height: 14.w),
                  RichText(
                      text: TextSpan(children: [
                    TextSpan(
                        text: info['discount'] ? '' : '￥',
                        style: TextStyle(
                            color: EsColors.Money,
                            fontSize: EsSizes.SM * 2.sp,
                            fontWeight: EsFontWeights.SemiBold)),
                    TextSpan(
                        text: info['num'],
                        style: TextStyle(
                            color: EsColors.Money,
                            fontSize: 44.sp,
                            fontWeight: EsFontWeights.SemiBold)),
                    TextSpan(
                        text: info['discount'] ? '折' : '',
                        style: TextStyle(
                            color: EsColors.Money,
                            fontSize: EsSizes.SM * 2.sp,
                            fontWeight: EsFontWeights.SemiBold)),
                    TextSpan(
                        text: '  ' + info['tips'],
                        style: TextStyle(
                            color: EsColors.Money,
                            fontSize: EsSizes.XS * 2.sp,
                            fontWeight: EsFontWeights.SemiBold)),
                  ])),
                  SizedBox(height: 20.w),
                ],
              ),
            ),
            SizedBox(width: 24.w),
            Visibility(
                visible:
                    info['receive'] == '100' || info['maxHave'] == info['have'],
                child: Image.asset(
                  _getImagePath(info),
                  width: 120.w,
                  height: 120.w,
                )),
            Visibility(
              visible: !(info['receive'] == '100' ||
                  info['maxHave'] == info['have']),
              child: Column(
                children: [
                  Text(
                    '已抢' + info['receive'] + '%',
                    style: TextStyle(
                        color: EsColors.TitleSecondary,
                        fontSize: EsSizes.XXS * 2.sp,
                        fontWeight: EsFontWeights.Normal),
                  ),
                  SizedBox(height: 10.w),
                  Container(
                    clipBehavior: Clip.antiAlias,
                    decoration: BoxDecoration(
                        color: Color(0xffefefef),
                        borderRadius: BorderRadius.circular(6.w)),
                    width: 140.w,
                    height: 10.w,
                    child: Row(children: [
                      Expanded(
                          flex: int.parse(info['receive']),
                          child: Container(color: EsColors.Money)),
                      Expanded(
                          flex: 100 - int.parse(info['receive']),
                          child: SizedBox())
                    ]),
                  ),
                  SizedBox(height: 20.w),
                  Text(
                    '限领' +
                        info['maxHave'] +
                        '张' +
                        (int.parse(info['have'] ?? '0') > 0
                            ? ' 已领${info['have']}张'
                            : ''),
                    style: TextStyle(
                        color: EsColors.TitleSecondary,
                        fontSize: EsSizes.XXS * 2.sp,
                        fontWeight: EsFontWeights.Normal),
                  ),
                  SizedBox(height: 16.w),
                  EsOutLineButton(
                    '立即领取',
                    padding:
                        EdgeInsets.symmetric(vertical: 6.w, horizontal: 24.w),
                    bgColor: EsColors.Money,
                    fontSize: EsSizes.XXS * 2.sp,
                    textColor: EsColors.White,
                    borderColor: EsColors.Money,
                    onTap: () {
                      setState(() {
                        info['have'] =
                            (int.parse(info['have'] ?? 0) + 1).toString();
                      });
                    },
                  )
                ],
              ),
            ),
            SizedBox(width: 24.w),
          ],
        ),
      ),
    );
  }

  String _getImagePath(Map<String, dynamic> info) {
    /// 此部分image逻辑仅做展示区分
    if (info['receive'] == '100') {
      return 'assets/images/robbedAll_image.png';
    } else if (info['receive'] != '100' && info['maxHave'] == info['have']) {
      return 'assets/images/received_image.png';
    } else {
      return 'assets/images/used.png';
    }
  }
}
